<?php
/**
 * customer后台 肤质检测数据
 *
 * Author: hezhizheng
 * Date: 2018/5/10
 * Created by Panxsoft.
 */

namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\ApiController;
use App\Http\Middleware\CustomerAuth;
use App\Http\Requests\Wechat\SkinRecordIndexRequest;
use App\Http\Requests\Wechat\SkinRecordListRequest;
use App\Models\Admin\CustomerAdmin;
use App\Models\Customer\CustomerRelateWaxSkin;
use App\Models\OpenWechat\WechatUser;
use App\Models\Store\SkinRecord;
use App\Models\Store\Store;
use App\Models\Store\StorePivotWechatUser;
use App\Services\OpenWechat\WechatUserRepository;
use App\Services\Presenters\Admin\HmSkinRecordPresenter;
use App\Services\Presenters\Admin\WaxSkinRecordPresenter;
use App\Services\Presenters\HmSkinData;
use App\Services\Presenters\WaxSkinData;
use App\Services\Repositories\SkinRecord\SkinRecordRepository;
use App\Services\Utils\Guard;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class SkinRecordController extends ApiController
{
    const ROUTES = [
        'index'                 => 'api.admin.customer.skin-record.index',
        'list'                  => 'api.admin.customer.skin-record.list',
        'showPieChartData'   => 'api.admin.customer.skin-record.show-pie-chart-data',
        'indexUsageCount'     => 'api.admin.customer.skin-record.index-usage-count',
        'indexGroupByStores' => 'api.admin.customer.skin-record.index-group-by-stores',
    ];

    protected $skinRecordRepository;
    protected $wechatUserRepository;

    public function __construct(SkinRecordRepository $skinRecordRepository,
                                WechatUserRepository $wechatUserRepository)
    {
        $this->skinRecordRepository = $skinRecordRepository;
        $this->wechatUserRepository = $wechatUserRepository;
    }

    /**
     * @deprecated
     *
     * 客户后台 - 测肤功能使用人次统计数据
     * @test
     *
     * @throws \Exception
     */
    public function deprecated_indexUsageCount()
    {
        $this->checkCustomer();

        $customer = Guard::customerAdmin()->customer;

        $store_ids = $customer->stores->pluck('id')->all();

        $skin_record_ids = (new SkinRecord)
            ->whereIn('store_id', $store_ids)
            ->pluck('id')
            ->all();

        $wechat_user_ids = StorePivotWechatUser::storesWechatUsersIds($store_ids);

        $latest_record_date = (new SkinRecord)
                ->whereIn('store_id', $store_ids)
                ->oldest('created_at')
                ->first()->created_at ?? null;

        $skin_record_date = $latest_record_date
            ? $this->skinRecordRepository->formatStartEndDateRange($latest_record_date)
            : null;

        $all_count = $this->querySkinCount($store_ids, $skin_record_ids, $wechat_user_ids);
        $hm_count = $this->querySkinCount($store_ids, $skin_record_ids, $wechat_user_ids, SkinRecord::HM);
        $wax_count = $this->querySkinCount($store_ids, $skin_record_ids, $wechat_user_ids, SkinRecord::WAX);

        return $this->response(compact('all_count', 'hm_count', 'wax_count', 'skin_record_date'));
    }

    /**
     * 客户后台 - 测肤功能使用人次统计数据
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function indexUsageCount()
    {
        $this->checkCustomer();

        $customer = Guard::customerAdmin()->customer;
        $store_ids = $customer->stores->pluck('id')->all();

        $usage_count_info = $this->skinRecordRepository->storesUsageCountInfo($store_ids);

        return $this->response($usage_count_info);
    }

    /**
     * 后台客户,肤质检测数据管理,微信用户的所有肤质检测数据
     * @test
     *
     * @param SkinRecordListRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function skinRecordList(SkinRecordListRequest $request)
    {
        $this->checkCustomer();

        /** @var WechatUser $wechat_user */
        $wechat_user = WechatUser::findByOpenId($request->openid);

        $this->checkItemExist($wechat_user,trans('app.wechat_user_error'));

        $store_ids = $wechat_user->skinRecords->pluck('store_id')->all();

        $skin_detector_id = (int) $request->skin_detector_id;

        $skin_suggests = $this->skinRecordRepository->getCustomerSkinSuggests($skin_detector_id, Guard::customerAdmin()->customer_id);

        $skin_record_ids = $this->skinRecordRepository->getSkinRecordIdsForList($skin_detector_id, $wechat_user);

        $skin_records = $this->skinRecordRepository->normalizeSkinRecordList($request, $wechat_user, $skin_record_ids, $store_ids, $skin_suggests);

        return $this->response(compact('skin_records'));

    }

    /**
     * 客户后台,肤质检测数据管理,饼图展示hm、wax测肤统计数据
     * @test
     *
     * @throws \Exception
     * @return array|\Illuminate\Http\Response
     */
    public function showPieChartData()
    {
        $this->checkCustomer();

        $customer_id = CustomerRelateWaxSkin::CUSTOMER_ID_DEFAULT;

        $customer = Guard::customerAdmin()->customer;

        $store_ids = $customer->stores->pluck('id')->all();

        $hm_skin = HmSkinRecordPresenter::storesUsersStatisticLabelGroupData($store_ids, $customer_id);

        $wax_skin = WaxSkinRecordPresenter::storesUsersStatisticLevelGroupData($store_ids, $customer_id);

        return $this->response(compact('hm_skin', 'wax_skin'));
    }

    /**
     * 后台客户,肤质检测数据管理,微信用户去过的店铺信息
     * @test
     *
     * @param Request $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function indexGroupByStores(Request $request)
    {
        $this->checkCustomer();

        $wechat_user = WechatUser::findByOpenId($request->openid);
            $this->checkItemExist($wechat_user,trans('app.wechat_user_error'));

        $customer = Guard::customer();

        $wx_user_customer_store_ids = $wechat_user
            ->skinRecords()
            ->whereIn('store_id', $customer->stores()->pluck('id'))
            ->pluck('store_id')
            ->all();

        /** @var LengthAwarePaginator|Store[] $stores */
        $stores = $customer->stores()
            ->whereKey($wx_user_customer_store_ids)
            ->select(['id', 'name', 'store_img', 'address'])
            ->paginate($request->per_page ?: 15);

        $records_grp_by_store_detector = $this->wechatUserRepository
            ->getSkinRecordsGroupByStoreIdSkinDetector($wx_user_customer_store_ids, $wechat_user);

        $stores->each(function (Store $store) use ($records_grp_by_store_detector) {
            $store_records_grp_by_detector = $records_grp_by_store_detector[$store->id];

            $hm_skin_count = $store_records_grp_by_detector[SkinRecord::HM][0]['skin_record_count'] ?? 0;
            $wax_skin_count = $store_records_grp_by_detector[SkinRecord::WAX][0]['skin_record_count'] ?? 0;
            $store->hm_skin_count = $hm_skin_count;
            $store->wax_skin_count = $wax_skin_count;
            $store->all_skin_count = $wax_skin_count + $hm_skin_count;
        });

        return $this->response(compact('stores'));
    }

    /**
     * @param $store_ids
     * @param $skin_record_ids
     * @param $wechat_user_ids
     * @param int $skin_record_id
     * @return mixed
     */
    private function querySkinCount($store_ids, $skin_record_ids, $wechat_user_ids, int $skin_record_id = 0)
    {
        $is_wax = $skin_record_id === SkinRecord::WAX;
        $is_hm = $skin_record_id === SkinRecord::HM;

        $count = (new WechatUser)
            ->whereIn('id', $wechat_user_ids)
            ->filterSkinRecordByStores(1, $store_ids)
            ->when($is_wax, function ($query) use ($skin_record_ids) {
                /** @var WechatUser $query */
                $query->filterWaxSkinRecord(1, $skin_record_ids);
            })
            ->when($is_hm, function ($query) use ($skin_record_ids) {
                /** @var WechatUser $query */
                $query->filterHmSkinRecord(1, $skin_record_ids);
            })->count();

        return $count;
    }
}
